<template>
  <div class="loginPage">
    <div class="login">
      <h2 class="login-content">
        登 录
      </h2>
      <el-form ref="form" id="loginForm" :rules="rules" :model="form" label-width="60px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" name="userName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密　码" prop="password">
          <el-input type="password" v-model="form.password" name="password" auto-complete="off"></el-input>
        </el-form-item>
        <div>
          <el-button type="primary" style="width: 100%" @click="submit()">登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      let userNameRules = function (rule, value, callback) {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }
        callback()
      }
      let passWordRules = function (rule, value, callback) {
        if (!value) {
          return callback(new Error('密码不能为空'));
        }
        callback()
      }
      return {
        form: {
          userName: 'admin',
          password: '123456'
        },
        rules: {
          userName: [{
            validator: userNameRules,
            trigger: 'blur'
          }],
          password: [{
            validator: passWordRules,
            trigger: 'blur'
          }]
        }
      }
    },
    mounted() {
    },
    methods: {
      submit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$ajax.post('/index/login', this.form)
              .then(req => {
                console.info(req)
                if (req.data.code === -1) {
                  this.$message.error({message: req.data.msg, duration: 5000});
                  return
                }
                if (this.$route.query.redirect) {
                  this.$router.replace({
                    path: this.$route.query.redirect
                  })
                } else {
                  this.$router.push({
                    path: '/'
                  })
                }
              })
              .catch(err => {
                console.info(err)
              })
          } else {
            return false;
          }
        })
      }
    }
  }
</script>

<style scoped lang="less">
  @import "login";
</style>
